package org.database.config;

import com.mybatisflex.core.datasource.DataSourceShardingStrategy;
import com.mybatisflex.core.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.database.annotation.ForceDB;
import org.database.condition.DateBaseConditional;
import org.database.enums.Type;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * DateBaseStrategy
 *
 * @author grl
 * @date 2024/1/5
 */
@Slf4j
@Component
@Conditional(value = DateBaseConditional.class)
public class DateBaseStrategyConfiguration implements DataSourceShardingStrategy {

    @Override
    public String doSharding(String currentDataSourceKey, Object mapper, Method mapperMethod, Object[] methodArgs) {
        ForceDB annotation = mapperMethod.getAnnotation(ForceDB.class);
        if (annotation != null) {
            Type type = annotation.type();
            if (Type.write.equals(type)) {
                log.debug("读写分离切换到写库");
                return "master*";
            } else {
                log.debug("读写分离切换到读库");
                return "slave*";
            }
        }
        return switchDbName(mapperMethod);
    }

    private String switchDbName(Method mapperMethod) {
        if (StringUtil.startsWithAny(mapperMethod.getName(),
                "insert", "delete", "update")) {
            log.debug("读写分离切换到写库");
            return "master*";
        }
        log.debug("读写分离切换到读库");
        return "slave*";
    }
}
